package com.chj.comp.common.rabbitmq.sender;

import com.alibaba.fastjson.JSON;
import com.chj.comp.common.rabbitmq.core.AbstractSender;
import com.chj.comp.common.rabbitmq.message.MessageEntity;
import com.chj.comp.common.rabbitmq.queue.MqDirectQueue;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

/**
 *
  * @Description: 发布订阅模型-路由类型消息发送
  * @author cuihui
  * @date 2022-06-09
  *
 */
@Slf4j
public class MqDirectSender extends AbstractSender<Message> {

    public MqDirectSender(RabbitTemplate rabbitTemplate) {
        super(rabbitTemplate);
    }

    @Override
    public String send(Message message) {
        try {
            // 发送消息：消息发送至指定路由
            MessageEntity messageEntity = JSON.parseObject(message.getBody(), MessageEntity.class);
            if(messageEntity.getName().contains("1")){
                rabbitTemplate.convertAndSend(MqDirectQueue.EXCHANGE_NAME, MqDirectQueue.ROUTING_KEY1, message);
            }else{
                rabbitTemplate.convertAndSend(MqDirectQueue.EXCHANGE_NAME, MqDirectQueue.ROUTING_KEY2, message);
            }
        } catch (Exception e) {
            log.error("发送消息失败：{}", message.getMessageProperties().getMessageId());
            return null;
        }
        return message.getMessageProperties().getMessageId();
    }

}
